package com.example.griddemo.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import com.bumptech.glide.Glide;
import com.example.griddemo.R;
import com.example.griddemo.activity.GoodsListActivity;
import com.example.griddemo.adapter.CategoryAdapter;
import com.example.griddemo.adapter.GridCategoryAdapter;
import com.example.griddemo.api.ApiService;
import com.example.griddemo.interfaces.ResponseCallback;
import com.example.griddemo.viewmodel.Category;
import com.example.griddemo.viewmodel.CategoryResponse;
import com.example.griddemo.viewmodel.ResponseData;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CategoryFragment extends Fragment {

    private ListView left_category_list;
    private GridView category_grid;
    private ImageView category_image;
    private TextView right_category_item_text;

    private List<Category> categoryList;
    private GridCategoryAdapter gridAdapter;
    private Map<Integer, List<Category>> subCategoryMap = new HashMap<>();
    private Map<Integer, String> categoryPicMap = new HashMap<>();

    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        initViews(view);
        loadCategoryData();
        return view;
    }

    private void initViews(View view) {
        left_category_list = view.findViewById(R.id.left_category_list);
        category_grid = view.findViewById(R.id.category_grid);
        category_image = view.findViewById(R.id.category_image);
        right_category_item_text = view.findViewById(R.id.right_category_item_text);

        gridAdapter = new GridCategoryAdapter(getActivity(), new ArrayList<>()); // 使用getActivity()获取Context
        gridAdapter.setOnItemClickListener(category -> {
            if (getActivity() != null && !getActivity().isFinishing()) {
                Intent intent = new Intent(getActivity(), GoodsListActivity.class);
                intent.putExtra("categoryId", category.getId());
                startActivity(intent);
                // 添加过渡动画
                getActivity().overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
            }
        });
        category_grid.setAdapter(gridAdapter);
    }

    private void loadCategoryData() {
        ApiService.getCategoryData(new ResponseCallback<ResponseData<CategoryResponse>>() {
            @Override
            public void onSuccess(ResponseData<CategoryResponse> response) {
                CategoryResponse data = response.getData();
                categoryList = data.getCategoryList();

                for (Category category : categoryList) {
                    categoryPicMap.put(category.getId(), category.getPicUrl());
                }

                left_category_list.setAdapter(new CategoryAdapter(requireContext(), categoryList));
                setupCategoryClickListener();

                if (!categoryList.isEmpty()) {
                    loadSubCategoryData(categoryList.get(0).getId());
                }
            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void setupCategoryClickListener() {
        left_category_list.setOnItemClickListener((parent, view, position, id) -> {
            Category selected = categoryList.get(position);
            loadSubCategoryData(selected.getId());
        });
    }

    private void loadSubCategoryData(int categoryId) {
        if (subCategoryMap.containsKey(categoryId)) {
            updateCategoryDisplay(categoryId);
            return;
        }

        ApiService.getSubCategoryData(categoryId, new ResponseCallback<ResponseData<CategoryResponse>>() {
            @Override
            public void onSuccess(ResponseData<CategoryResponse> response) {
                List<Category> subCategories = response.getData().getCurrentSubCategory();
                subCategoryMap.put(categoryId, subCategories);
                updateCategoryDisplay(categoryId);
            }

            @Override
            public void onError(String error) {

            }
        });
    }

    private void updateCategoryDisplay(int categoryId) {
        Glide.with(this)
                .load(categoryPicMap.get(categoryId))
                .into(category_image);

        right_category_item_text.setText(categoryList.stream()
                .filter(c -> c.getId() == categoryId)
                .findFirst()
                .map(Category::getDesc)
                .orElse(""));

        gridAdapter.updateData(subCategoryMap.get(categoryId));
    }
}